<?php

class SetIngredientsAction extends CAction
{
    private $_succ=false;
    private $_recipe;

    private function renderView()
    {
        $this->controller->layout='simple';
        $this->controller->render('setIngredients',array('succ'=>$this->_succ, 'recipe'=>$this->_recipe));    
    }

    private function getIngredients()
    {
        $ingredients=array();
        $inputNameList = $_POST['ingredientsList'];
        if(isset($inputNameList)) {
            foreach($inputNameList as $inputName) {
                $name=$_POST['name'.$inputName];
                $quanlity=$_POST['quanlity'.$inputName];
                if(!empty($name) || !empty($quanlity)) {
                    $ingredients[] = new Ingredient($name, $quanlity);
                }
            }
        }
        return $ingredients;
    }
    
    public function run()
    {
        if(!isset($_GET['id']))
            throw new CHttpException(400,'the request is invalid');
    
        $this->_recipe=Recipe::loadObjectById($_GET['id'],array('userId','servings','ingredients'));
        if($this->_recipe===null)
            throw new CHttpException(404,'The requested recipe does not exist.');
        if($this->_recipe->userId!=Yii::app()->user->id)
            throw new CHttpException(403,'cannot edit the recipe not belong to you');

        if(!isset($_POST['servings'])){
            $this->renderView();
            return;
        }
        
        $servings = $_POST['servings'];
        $ingredients = $this->getIngredients();
        $changedAttr = array();            
        if($this->_recipe->servings !== $servings) {
            $this->_recipe->servings = $servings;
            $changedAttr[]='servings';
        }
        if($this->_recipe->ingredients!=$ingredients) {
            $this->_recipe->ingredients = $ingredients;
            $changedAttr[]='ingredients';            
        }

        if(empty($changedAttr)) {
            $this->_succ=true;
        }
        else {
            $changedAttr[]='updateTime';
            $this->_succ=Recipe::saveObject($this->_recipe, $changedAttr);
        }
        
        $this->renderView();
    }
}
  
?>